var http = require("http");
var readline = require('readline');
var fs = require('fs');

function readarr( filename, callback )//创建读取文件的函数，读取完之后回调
{
    var filearr;
    var file = fs.createReadStream( filename );//创建读取文件的流
    var line_arr = readline.createInterface(
        {
            input:file
        }
    );//创建按行读取的对象
    var arr = new Array();

    line_arr.on('line', (line) => {
        arr.push( line );
        //        console.log( arr );
    });//按行读取

    line_arr.on('close', () =>{
        filearr = arr.concat();
        callback( filearr );//回调
    });
}

function pic_server( filename, port, callback )//创建服务器的函数，
{
    
    readarr( filename, ( filearr ) => {
        
        console.log("Read data.txt Finished");
        console.log( "The file has " + filearr.length + " lines" );//读取文件

        http.createServer( (req, res) => {
            
            res.writeHead(200, {'Content-Type': 'text/plain'});

            var whicharr = Math.floor( Math.random()*filearr.length );

            res.end( filearr[whicharr] );
        }).listen( port - 1 );//文字API

        http.createServer( (req, res) => {
            
            res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});

            var whicharr = Math.floor( Math.random()*filearr.length );

            res.end( `<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Zhaose's repo</title>
    <style>
      body
      {
	  background-color:#d0e4fe;
      }
      h1
      {
	  color:orange;
	  text-align:center;
      }
      p
      {
	  font-family:"Times New Roman";
	  font-size:20px;
          background-color:#dddddd;
          text-align: center;
      }
    </style>
  </head>
  <body>
    <h1>zhaose's API</h1>
    <p><img src="` + filearr[whicharr] + `"/></p>
  </body>
</html>` );
        }).listen( port );//页面API

        http.createServer( (req, res) => {

            var whicharr = Math.floor( Math.random()*filearr.length );

            var url = filearr[whicharr];
            
            res.writeHead(301, {'Location': url });

            res.end();
        }).listen( port + 1 );//跳转API

        console.log('Text Server running at http://127.0.0.1:' + (port - 1) + '/');
        console.log('Html Server running at http://127.0.0.1:' + port + '/');
        console.log('301  Server running at http://127.0.0.1:' + (port + 1) + '/');
        //输出log
        
    });


    callback();//回调
    
}

pic_server( 'data.txt', 2881, () => {

    console.log( "Starting Server Done!" );

});


